/*
 * Copyright (C) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package tako.wisers.com.android.apis.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.io.IOUtils;

import tako.wisers.com.android.apis.http.HttpGeter;

/**
 * Utilities for loading a bitmap from a URL
 * 
 */
public class BitmapUtils {

	private static final String TAG = "Panoramio";

	private static final int IO_BUFFER_SIZE = 300 * 1024;

	private static final int CUT_COUNT_SIZE = 60 * 1024;

	public static ThreadGroup GROUP_BITMAP = new ThreadGroup("BITMAP Group");

	/**
	 * Loads a bitmap from the specified url. This can take a while, so it
	 * should not be called from the UI thread.
	 * 
	 * @param url
	 *            The location of the bitmap asset
	 * 
	 * @return The bitmap, or null if it could not be loaded
	 */
	public Bitmap loadBitmap(String url) {
		Bitmap bitmap = null;
		InputStream in = null;

		if (url == null) {
			return null;
		}
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(10000);

			if (conn.getResponseCode() != 200) {
				return null;
			}
			in = conn.getInputStream();
			byte[] data = IOUtils.toByteArray(in);
			if (data.length > IO_BUFFER_SIZE) {
				return null;
			}
			bitmap = loadBitmap(data);
		} catch (IOException e) {
			Log.e(TAG, "Could not load Bitmap from: " + url);
		} finally {
			if (conn != null) {
				IOUtils.closeQuietly(in);
				conn.disconnect();
			}
		}
		System.gc();
		return bitmap;
	}

	public Bitmap loadBitmap(byte[] data) {
		if (data == null)
			return null;
		int len = data.length;
		if (len > CUT_COUNT_SIZE) {
			BitmapFactory.Options opts=new BitmapFactory.Options();
			opts.inSampleSize = 2;
			return BitmapFactory.decodeByteArray(data, 0, len, opts);
		} else {
			return BitmapFactory.decodeByteArray(data, 0, len);
		}
	}

	public static boolean bitmapLoadFinish() {
		return GROUP_BITMAP.activeCount() == 0;
	}

	// /**
	// * Copy the content of the input stream into the output stream, using a
	// * temporary byte array buffer whose size is defined by
	// * {@link #IO_BUFFER_SIZE}.
	// *
	// * @param in
	// * The input stream to copy from.
	// * @param out
	// * The output stream to copy to.
	// * @throws IOException
	// * If any error occurs during the copy.
	// */
	// private static void copy(InputStream in, OutputStream out)
	// throws IOException {
	// if (in == null) {
	// return;
	// }
	// byte[] b = new byte[IO_BUFFER_SIZE];
	// int read;
	// while ((read = in.read(b)) != -1) {
	// out.write(b, 0, read);
	// }
	// }

}